package org.looop.chuck.persistence.impl;

import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.concurrent.Semaphore;

import org.looop.chuck.domain.AppInfo;
import org.looop.chuck.persistence.PersistenceManager;

public class FileAppInfoWriter implements PersistenceManager {
	private Semaphore semaphore = new Semaphore(1);
	private BufferedWriter writer;
	
	public FileAppInfoWriter(String filePath, String charset) throws UnsupportedEncodingException, FileNotFoundException {
		writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath), charset));
	}

	@Override
	public int writeAppInfo(List<AppInfo> appInfoList) throws InterruptedException {
		if(appInfoList == null || appInfoList.size() == 0){
			return 0;
		}
		int count = 0;
		semaphore.acquire();
		try{
			for(AppInfo appInfo : appInfoList){
				count += writeApp(appInfo);
			}
		}finally{
			semaphore.release();
		}
		return count;
	}

	protected int writeApp(AppInfo appInfo) {
		int count = 0;
		try{
			writer.newLine();
			writer.write(appInfo.toString());
			writer.flush();
			count++;
		}catch(IOException e){
			e.printStackTrace();
		}
		return count;
	}

	@Override
	public void release() throws IOException {
		if(writer != null){
			writer.close();
		}
	}

}
